<?php

namespace App\Service\OpenShop\Pdf;

use App\Service\OpenShop\Feishu\ConfigService;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kuafu\File\FileUtil;
use Uvinum\PDFWatermark\FpdiPdfWatermarker;
use Uvinum\PDFWatermark\Pdf;
use Uvinum\PDFWatermark\Position;
use Uvinum\PDFWatermark\Watermark;

class PdfMakerService
{
    const FILE_NAME_PREFIX = 'kuafu_tiger_open_shop';
    // 字体，苹方
    const FONT = '96/ec/2276d8e77453e0e44f1e9633ee513396f2eeabb3d330f9e9306343b25fd9.ttf';

    /**
     * 通过配置文件获取内容
     *
     * @param string $fileName
     * @param string $key
     * @return string|array
     * @throws \Exception
     */
    public static function getConfig(string $fileName = '', string $key = '')
    {
        $fileList = ConfigService::config("openShop")["pdfManualFile"];

//        $fileList = [
//            'manager'       => [
//                'fileName' => 'manager.pdf',
//                'fileUrl'  => 'f0/75/2ee77efcaee0a50ecf81a4f0f1ce25b6a297ccb58c53c1b3820fdcbbada0.pdf',
//                'version'  => '20220505',
//                'name'     => '店长管理手册',
//                'weight'   => 1,
//            ],
//            'operation'     => [
//                'fileName' => 'operation.pdf',
//                'fileUrl'  => 'b9/82/35ba963774a3028b3093d304c4ed7951a36f641cecfeaeedfe5491c5395c.pdf',
//                'version'  => '20220926',
//                'name'     => '门店运营手册',
//                'weight'   => 2,
//            ],
//            'sop'           => [
//                'fileName' => 'sop.pdf',
//                'fileUrl'  => '88/d1/c2f4639b0ddfa316e5d29e064fd6aca5c7605b423e0d92a0479d3689b0b8.pdf',
//                'version'  => '20221003',
//                'name'     => '产品标准SOP手册',
//                'weight'   => 3,
//            ],
//            'qualification' => [
//                'fileName' => 'qualification.pdf',
//                'fileUrl'  => '0c/03/2e371fe7dab2ae8bfe52b6018d605ca48251379b4275e02fbdbf69775285.pdf',
//                'version'  => '20211102',
//                'name'     => '夸父炸串资质证明',
//                'weight'   => 4,
//            ],
//            'cityType'      => [
//                'fileName' => 'cityType.pdf',
//                'fileUrl'  => '14/ea/1f461a6cd0779d75465dfe6f21cca8fe2f94b17442f7f7fde607c250a727.pdf',
//                'version'  => '20220601',
//                'name'     => '商户通费用城市分级表',
//                'weight'   => 5,
//            ],
//            'franchise'     => [
//                'fileName' => 'franchise.pdf',
//                'fileUrl'  => '4e/1e/fcdc514ec1654aeac45f4ea2197ddace0f9bc22699d55ca795c6e8d01d41.pdf',
//                'version'  => '20220601',
//                'name'     => '特许经营信息披露函',
//                'weight'   => 6,
//            ],
//        ];
//        echo json_encode($fileList);

        return empty($fileName) ? $fileList : (empty($key) ? $fileList[$fileName] ?? [] : $fileList[$fileName][$key] ?? '');
    }

    protected static function prepareResource()
    {
        if (!is_dir(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX)) {
            @unlink(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX);
            mkdir(sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX, 0777, true);
        }
        if (!static::checkSha256('font.ttf', static::FONT)) {
            static::downloadFile(static::FONT, static::tempFileName('font.ttf'));
        }
        $fileList = self::getConfig();
        foreach ($fileList as $file) {
            if (!static::checkSha256($file['fileName'], $file['fileUrl'])) {
                static::downloadFile($file['fileUrl'], static::tempFileName($file['fileName']));
            }
        }
    }


    /**
     * 下载oss文件到本地
     * @param string $url
     * @param string $localPath
     * @return void
     */
    protected static function downloadFile(string $url, string $localPath)
    {
        @unlink($localPath);
        file_put_contents($localPath, file_get_contents(FileUtil::domain() . '/' . $url));
    }

    /**
     * 固定的文件在本地的临时地址
     * @param $name
     * @return string
     */
    protected static function tempFileName($name): string
    {
        return sys_get_temp_dir() . '/' . static::FILE_NAME_PREFIX . '/' . $name;
    }

    /**
     * 检查文件指纹
     * @param $name
     * @param $url
     * @return bool
     */
    protected static function checkSha256($name, $url): bool
    {
        $tempFilename = static::tempFileName($name);
        if (!is_readable($tempFilename)) {
            return false;
        }
        $sha256 = substr(str_replace('/', '', $url), 0, 64);
        if ($sha256 != hash_file('sha256', $tempFilename)) {
            return false;
        }
        return true;
    }

    public static function operationPdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(793, 1123);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 1500; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('operation.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }

    public static function managerPdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(793, 1123);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 1500; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('manager.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }

    /**
     * 生成sop水印PDF
     * @param string $text
     * @return string
     */
    public static function sopPdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(1123, 793);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 900; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('sop.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }

    /**
     * 夸父炸串资质
     * @param string $text
     * @return string
     */
    public static function qualificationPdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(793, 1123);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 1500; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('qualification.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }

    /**
     * 夸父炸串资质
     * @param string $text
     * @return string
     */
    public static function cityTypePdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(793, 1123);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 1500; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('cityType.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }


    /**
     * 特许经营信息披露函
     * @param string $text
     * @return string
     */
    public static function franchisePdf(string $text = '山治9999 机密信息 严禁外传'): string
    {
        static::prepareResource();
        $image = Image::canvas(793, 1123);
        for ($i = 0; $i <= 1500; $i += 700) {
            for ($j = 0; $j <= 1500; $j += 400) {
                $image->text($text, $i, $j, function ($font) {
                    $font->file(static::tempFileName('font.ttf'));
                    $font->size(45);
                    $font->color([10, 10, 10, 0.08]);
                    $font->align('center');
                    $font->valign('top');
                    $font->angle(30);
                });
            }
        }
        // 临时水印文件
        $watermarkPNG = static::tempFileName(Str::random(10) . '.png');
        $image->save($watermarkPNG);
        $image       = null;
        $newPdf      = static::tempFileName(Str::random(10) . '.pdf');
        $pdf         = new Pdf(static::tempFileName('franchise.pdf'));
        $watermark   = new Watermark($watermarkPNG);
        $watermarker = new FpdiPdfWatermarker($pdf, $watermark);
        $watermarker->setPosition(new Position('MiddleCenter'));
        $watermarker->savePdf($newPdf);
        @unlink($watermarkPNG);
        $watermarker = null;
        return $newPdf;
    }
}
